package com.xnyzc.lhy.order.service.impl.approval;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.component.convert.DateToStringConverter;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.approval.EApprovalMatter;
import com.xnyzc.lhy.common.penum.approval.EApprovalName;
import com.xnyzc.lhy.common.penum.approval.EApprovalOrderStatus;
import com.xnyzc.lhy.common.penum.approval.EApprovalTaskStatus;
import com.xnyzc.lhy.common.penum.vehicle.EvehicleType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.ResultListUtil;
import com.xnyzc.lhy.order.entity.approval.OaApprovalList;
import com.xnyzc.lhy.order.entity.approval.OaApprovalTask;
import com.xnyzc.lhy.order.entity.order.OaCOrderApprovalOfficial;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.order.entity.user.OaCUser;
import com.xnyzc.lhy.order.mapper.approval.OaApprovalListMapper;
import com.xnyzc.lhy.order.mapper.approval.OaApprovalTaskMapper;
import com.xnyzc.lhy.order.mapper.order.OaCOrderApprovalOfficialMapper;
import com.xnyzc.lhy.order.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.order.mapper.user.OaCUserMapper;
import com.xnyzc.lhy.order.service.approval.IOaApprovalListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 审批列表
 * @Author zhuyubin
 * @Date 2019/8/13 10:41
 **/
@Service
public class OaApprovalListServiceImpl implements IOaApprovalListService {

    @Autowired
    private OaApprovalListMapper oaApprovalListMapper;
    @Autowired
    private OaCOrderApprovalOfficialMapper oaCOrderApprovalOfficialMapper;
    @Autowired
    private OaApprovalTaskMapper oaApprovalTaskMapper;
    @Autowired
    private OaCUserMapper oaCUserMapper;
    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    /**
     * 审批列表
     * @param userId 用户id
     * @param tag 用户来源
     * @param type 类型
     * @param current 当前页
     * @return
     */
    @Override
    public IPage selectApprovalPage(Long userId, String tag, Integer type, Long current){
        IPage<OaApprovalList> page = new Page<>();
        page.setCurrent(current);
        IPage<OaApprovalList> oaApprovalListIPage;
        // 我的申请
        if (type.equals(0)){
            oaApprovalListIPage = oaApprovalListMapper.selectApprovalPage(page, tag, null, userId);
        }
        // 我的审批
        else if (type.equals(1)){
            oaApprovalListIPage = oaApprovalListMapper.selectApprovalPage(page, tag, userId,  null);
        }
        // 非法类型
        else {
            throw PangException.create(EErrorCode.argCheckErr);
        }
        IPage<Map<String, Object>> result = new Page<>();
        result.setTotal(oaApprovalListIPage.getTotal());
        result.setCurrent(current);
        result.setSize(oaApprovalListIPage.getSize());
        result.setPages(oaApprovalListIPage.getPages());
        List<Map<String, Object>> list = new ArrayList();
        DateToStringConverter dateToStringConverter = new DateToStringConverter();
        for (OaApprovalList oaApprovalList : oaApprovalListIPage.getRecords()) {
            Map<String, Object> map = this.initApproval();
            map.put("approvalStatusName", EApprovalOrderStatus.findById(oaApprovalList.getApprovalStatus()).getDesc());
            map.put("approvalStatus", EApprovalOrderStatus.findById(oaApprovalList.getApprovalStatus()).getValue());
            map.put("createTime", dateToStringConverter.convert(oaApprovalList.getCreateTime()));
            map.put("name", CheckUtil.objIsEmpty(oaApprovalList.getName()) ? "" : oaApprovalList.getName());
            map.put("applyMatter", EApprovalMatter.findById(oaApprovalList.getApplyMatter()).getDesc());
            map.put("applyReason", CheckUtil.objIsEmpty(oaApprovalList.getApplyReason()) ? "" : oaApprovalList.getApplyReason());
            map.put("time", CheckUtil.objIsEmpty(oaApprovalList.getTime()) ? "" : dateToStringConverter.convert(oaApprovalList.getTime()));
            map.put("orderNo", oaApprovalList.getOrderNo());
            list.add(map);
        }
        result.setRecords(list);
        return result;
    }

    /**
     * 初始化审批列表对象字段
     * @return
     */
    private Map<String, Object> initApproval(){
        Map<String, Object> result = new HashMap<>(16);
        result.put("approvalStatusName", "");
        result.put("approvalStatus", -1);
        result.put("createTime", "");
        result.put("name", "");
        result.put("applyMatter", "");
        result.put("time", "");
        result.put("orderNo", "");
        result.put("applyReason", "");
        return result;
    }

    /**
     * 审批详情
     * @param userId 用户id
     * @param tag 租户
     * @param orderNo 审批订单号
     * @return
     */
    @Override
    public Map<String, Object> getApproval(Long userId, String tag, String orderNo){
        Map<String, Object> result = this.initGetApproval();
        // 审批任务表
        List<OaApprovalTask> oaApprovalTasks = oaApprovalTaskMapper.selectList(
                Wrappers.<OaApprovalTask>lambdaQuery()
                        .eq(OaApprovalTask::getOrderNo, orderNo)
                        .eq(OaApprovalTask::getTag, tag)
                        .orderByAsc(OaApprovalTask::getApprovalNode)
        );
        if (CheckUtil.objIsEmpty(oaApprovalTasks)){
            return result;
        }
        // 最终结果
        OaApprovalTask oaApprovalTask = oaApprovalTasks.get(0);
        // 根据申请人id查人
        OaCUser oaCUser = this.getOaCUser(oaApprovalTask.getApplyUserId(), null, tag);
        if (CheckUtil.objIsEmpty(oaCUser)){
            return result;
        }
        result.put("name", CheckUtil.strIsEmpty(oaCUser.getUserName()) ? "" : oaCUser.getUserName());
        result.put("phone", oaCUser.getUserPhone());
        result.put("avatar", CheckUtil.strIsEmpty(oaCUser.getUserName()) ? "" : oaCUser.getUserName().substring(0, 1));
        // 审批公务任务表
        OaCOrderApprovalOfficial oaCOrderApprovalOfficial = oaCOrderApprovalOfficialMapper.selectOne(
                Wrappers.<OaCOrderApprovalOfficial>lambdaQuery()
                        .eq(OaCOrderApprovalOfficial::getUserId, oaCUser.getUserId())
                        .eq(OaCOrderApprovalOfficial::getTag, tag)
                        .eq(OaCOrderApprovalOfficial::getOrderNo, orderNo)
        );
        if (CheckUtil.objIsEmpty(oaCOrderApprovalOfficial)){
            return result;
        }
        result.put("approvalStatus", EApprovalOrderStatus.findById(oaCOrderApprovalOfficial.getApprovalStatus()).getValue());
        result.put("approvalStatusName", EApprovalOrderStatus.findById(oaCOrderApprovalOfficial.getApprovalStatus()).getDesc());
        result.put("approvalId", CheckUtil.objIsEmpty(oaCOrderApprovalOfficial.getApprovalId()) ? "" : oaCOrderApprovalOfficial.getApprovalId().toString());
        result.put("approvalNode", oaCOrderApprovalOfficial.getApprovalNode());
        // 部门
        OaSysOffice oaSysOffice = oaSysOfficeMapper.selectOne(
                Wrappers.<OaSysOffice>lambdaQuery()
                        .eq(OaSysOffice::getOfficeId, oaCOrderApprovalOfficial.getOfficeId())
                        .eq(OaSysOffice::getTag, tag)
        );
        if (CheckUtil.objIsEmpty(oaSysOffice)){
            return result;
        }
        ResultListUtil resultListUtil = new ResultListUtil();
        resultListUtil
                .add(EApprovalName.approvalType.getName(), EApprovalName.approvalOffice.getName())
                .add(EApprovalName.transact.getName(), EApprovalMatter.findById(oaCOrderApprovalOfficial.getApplyMatter()).getDesc())
                .add(EApprovalName.carOffice.getName(), oaSysOffice.getName())
                .add(EApprovalName.carTime.getName(), new DateToStringConverter().convert(oaCOrderApprovalOfficial.getAppointment()))
                .add(EApprovalName.upCarAddress.getName(), CheckUtil.strIsEmpty(oaCOrderApprovalOfficial.getStartAddress()) ? "" : oaCOrderApprovalOfficial.getStartAddress())
                .add(EApprovalName.downCarAddress.getName(), CheckUtil.strIsEmpty(oaCOrderApprovalOfficial.getEndAddress()) ? "" : oaCOrderApprovalOfficial.getEndAddress())
                .add(EApprovalName.carType.getName(), EvehicleType.findById(oaCOrderApprovalOfficial.getVehicleType()).getValue())
                .add(EApprovalName.estimateMoney.getName(), CheckUtil.strIsEmpty(oaCOrderApprovalOfficial.getEstimatePrice()) ? "" : oaCOrderApprovalOfficial.getEstimatePrice())
                .add(EApprovalName.applyReason.getName(), CheckUtil.strIsEmpty(oaCOrderApprovalOfficial.getApplyReason()) ? "" : oaCOrderApprovalOfficial.getApplyReason());
        List<Map<String, Object>> list = resultListUtil.getList();
        result.put("list", list);
        // 下面列表
        List<Map<String, Object>> applyUserList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>(16);
        // 首个节点
        map.put("avatar", CheckUtil.strIsEmpty(oaCUser.getUserName()) ? "" : oaCUser.getUserName().substring(0, 1));
        map.put("name", CheckUtil.strIsEmpty(oaCUser.getUserName()) ? "" : oaCUser.getUserName());
        map.put("message", EApprovalName.apply.getName());
        map.put("approvalOpinion", "");
        map.put("time", new DateToStringConverter().convertFoMonth(oaCOrderApprovalOfficial.getCreateTime()));
        applyUserList.add(map);
        for (OaApprovalTask approvalTask : oaApprovalTasks) {
            OaCUser approvalUser = this.getOaCUser(null, approvalTask.getApprovalUserId(), tag);
            if (CheckUtil.objIsEmpty(approvalUser)){
                continue;
            }
            map = new HashMap<>(16);
            map.put("avatar", CheckUtil.strIsEmpty(approvalUser.getUserName()) ? "" : approvalUser.getUserName().substring(0, 1));
            map.put("name", CheckUtil.strIsEmpty(approvalUser.getUserName()) ? "" : approvalUser.getUserName());
            map.put("message", EApprovalTaskStatus.findById(approvalTask.getApprovalStatus()).getDesc());
            map.put("approvalOpinion", CheckUtil.objIsEmpty(approvalTask.getApprovalOpinion()) ? "" : approvalTask.getApprovalOpinion());
            map.put("time", new DateToStringConverter().convertFoMonth(approvalTask.getUpdateTime()));
            applyUserList.add(map);
            if (EApprovalTaskStatus.reject.getValue().equals(oaApprovalTask.getApprovalStatus())){
                resultListUtil.add(EApprovalName.denialReason.getName(), CheckUtil.objIsEmpty(oaApprovalTask.getApprovalOpinion()) ? "" : oaApprovalTask.getApprovalOpinion());
            }
        }
        result.put("applyUserList", applyUserList);
        result.put("isBy", false);
        result.put("isCancelBy", false);
        // 审批人查看
        List<OaApprovalTask> oaApprovalTaskList = oaApprovalTaskMapper.selectList(
                Wrappers.<OaApprovalTask>lambdaQuery()
                        .eq(OaApprovalTask::getApprovalUserId, userId)
                        .eq(OaApprovalTask::getTag, tag)
                        .eq(OaApprovalTask::getOrderNo, oaCOrderApprovalOfficial.getOrderNo())
        );
        if (oaApprovalTaskList.size() > 0){
            OaApprovalTask approvalTask = oaApprovalTaskList.get(0);
            if (EApprovalTaskStatus.pass.getValue().equals(approvalTask.getApprovalStatus()) ||
                    EApprovalTaskStatus.reject.getValue().equals(approvalTask.getApprovalStatus())){
                result.put("isBy", true);
                result.put("isCancelBy", true);
            }
            // 申请人是自己则显示按钮
            Long applyUserId = approvalTask.getApplyUserId();
            if (userId.equals(applyUserId)){
                result.put("isCancelBy", false);
                if (EApprovalOrderStatus.cancel.getValue().equals(oaCOrderApprovalOfficial.getApprovalStatus()) ||
                        EApprovalOrderStatus.pass.getValue().equals(oaCOrderApprovalOfficial.getApprovalStatus()) ||
                        EApprovalOrderStatus.reject.getValue().equals(oaCOrderApprovalOfficial.getApprovalStatus())){
                    result.put("isBy", true);
                    result.put("isCancelBy", true);
                }
            }
        }
        // 不是审批人
        else {
            if (EApprovalOrderStatus.cancel.getValue().equals(oaCOrderApprovalOfficial.getApprovalStatus()) || EApprovalOrderStatus.pass.getValue().equals(oaCOrderApprovalOfficial.getApprovalStatus()) || EApprovalOrderStatus.reject.getValue().equals(oaCOrderApprovalOfficial.getApprovalStatus())){
                result.put("isBy", true);
                result.put("isCancelBy", true);
            }
        }
        return result;
    }

    /**
     * 根据申请人id查人
     * @param applyUserId 申请人id 只能填写其中其中一个
     * @param approvalUserId 审批人id 只能填写其中其中一个
     * @param tag 租户
     * @return
     */
    private OaCUser getOaCUser(Long applyUserId, Long approvalUserId, String tag){
        Long userId;
        if (CheckUtil.objIsNotEmpty(approvalUserId)){
            userId = approvalUserId;
        } else {
            userId = applyUserId;
        }
        return oaCUserMapper.selectOne(
                Wrappers.<OaCUser>lambdaQuery()
                        .eq(OaCUser::getUserId, userId)
                        .eq(OaCUser::getTag, tag)
        );
    }

    /**
     * 初始化参数
     * @return
     */
    private Map<String, Object> initGetApproval(){
        Map<String, Object> result = new HashMap<>(16);
        result.put("name", "");
        result.put("phone", "");
        result.put("avatar", "");
        result.put("list", new ArrayList<>());
        result.put("applyUserList", new ArrayList<>());
        return result;

    }

}
